//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// 			VisualNovelToolkit		     /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe.	/_/_/_/_/_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.

#pragma warning disable 0414,0649

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace ViNoToolkit{

	[ExecuteInEditMode]
	public class GUIKAGInterpreter : MonoBehaviour {
		public TextAsset[] demos;

		public string url;
		private bool download;

		private string scenarioName;
		private string[] samples;
		private int selectedDemoID;
		private string scenarioScript = "";
		private Vector2 scrollPos = Vector2.zero;
		private bool show = true;

		void Awake(){
			samples = new string[ demos.Length ];
			for(int i=0;i<demos.Length;i++){
				samples[ i ] = demos[ i ].name;
			}
		}

		IEnumerator DownloadScenario(){
			// Start a download of the given URL
			WWW www = new WWW (url);

			// Wait for download to complete
			yield return www;		


			scenarioScript = www.text;
		}

		void OnGUI(){
			show = GUILayout.Toggle( show , "Show" );
			if( ! show ){
				return;
			}

			if( demos == null ){
				return;
			}

			GUILayout.BeginHorizontal();

				GUILayout.BeginVertical();

				GUILayout.Label( "Select a Scenario.");
				for( int i=0;i<demos.Length;i++){
					if( GUILayout.Button( demos[ i ].name , GUILayout.Width( 120f ) ) ){
						scenarioScript = demos[ i ].text;
	//					Run();
	//					show = false;
						break;
					}
				}
	//			GUILayout.Label( "                  ");
				GUILayout.EndVertical();			

				GUILayout.BeginVertical();

				scrollPos = GUILayout.BeginScrollView( scrollPos , GUILayout.Width( Screen.width - 120f ) , GUILayout.Height( 300f ) );

					GUILayout.BeginHorizontal();

					download = GUILayout.Toggle( download , "Download Script?" );

					if( download ){
						GUILayout.Label( "URL" );

						url = GUILayout.TextField( url );
						if( GUILayout.Button( "Download") ){
							StartCoroutine( "DownloadScenario" );
						}
					}

					GUILayout.EndHorizontal();

					scenarioScript = GUILayout.TextArea( scenarioScript );//,  );

				GUILayout.EndScrollView();

				GUILayout.BeginHorizontal();

					if( GUILayout.Button( "Clear" , GUILayout.Height( 40f ) ) ){
						scenarioScript = "";
					}		

					if( GUILayout.Button( "Run" , GUILayout.Height( 40f ) ) ){
						Run();
						show = false;
					}

				GUILayout.EndHorizontal();

				GUILayout.EndVertical();			

			GUILayout.EndHorizontal();
		}

		void Run(){
			GameObject scenario = new GameObject( scenarioName );
			ScenarioNode node = scenario.AddComponent<ScenarioNode>();
			node.m_PlayAtStart = false;
			FlagTable flagTbl = ScriptableObject.CreateInstance<FlagTable>();
			flagTbl.ClearFlags();

			node.flagTable = flagTbl;
			node.InterpretAndPlay( scenarioScript );
		}

	}
}